"""
file: test_check.py
Author: 城下秋草
Desc: 框架实战演示
"""
import os.path
from decimal import Decimal

import pytest

from pom.pages.CheckoutPage import CheckoutPage
from pom.pages.loginPage import LoginPage
from pom.pages.productPage import ProductPage
from pom.util.logger import logger
from pom.util.util import get_yml_data,get_json_data
from pom.util.paths import data_dir
from pom.util.custom_exception import ValidationError

products = get_yml_data(os.path.join(data_dir,"product.yml"))["products"]
users =[]
for u in get_json_data(os.path.join(data_dir,"users.json")):
    if u["id"] in ("正常登录","异常登录"):
        users.append(u)

@pytest.fixture(scope="class",params=users)
def login(page,request):
    login_page = LoginPage(page)
    login_page.visit("https://www.saucedemo.com")
    username = request.param["username"]
    password = request.param["password"]
    login_page.login(username, password)
    if not login_page.error_msg:
        yield page
    else:
        raise ValidationError(f"{username}没有成功登录")


class TestCheck:
    @pytest.mark.parametrize("prod_name",[products[0]["name"]])
    def test_add_product(self,login,prod_name):
        page = login
        logger.info(f"--------开始测试：添加商品{prod_name}")
        product_page = ProductPage(page)
        product_page.add_product(prod_name)
        assert product_page.get_badge_number() == 1

    def test_checkout(self,login):
        page = login
        product_page = ProductPage(page)
        checkout_page = CheckoutPage(page)

        count = 0
        tax_total = 0
        for product in products:
            prod_name = product["name"]
            product_page.add_product(prod_name)
            count += 1
            tax_total += Decimal(str(product["tax"]))

        assert product_page.get_badge_number() == count
        logger.info(f"添加了{count}个商品")
        product_page.goto_checkout()
        checkout_page.checkout()
        checkout_page.input_info()

        item_total = 0
        for price in checkout_page.get_prices():
            item_total += price

        assert item_total == checkout_page.get_total("item")
        assert tax_total == checkout_page.get_total("tax")
        assert item_total + tax_total == checkout_page.get_total("total")

        logger.info(f"商品总价：{item_total},tax:{tax_total}")

        checkout_page.finish()
        assert checkout_page.is_finished()
        logger.info("验证结算流程完成！")